<!--
 * @Author: Wangtao
 * @Date: 2020-11-06 21:48:51
 * @LastEditors: Wangtao
 * @LastEditTime: 2020-11-14 20:26:37
-->
<template>
  <div class="customer">
    <el-row class="customer-data-page">
      <el-row :id="'apassMicroCustomerData_'+ moduleType" class="page-container mp-micro" />
    </el-row>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
import { loadMicroApp, addGlobalUncaughtErrorHandler } from 'qiankun'
import { CommonModule } from '@/store/modules/common'
import { mpCallMsgEvent } from '@/store/modules/cti/ctiEvent'
@Component({
  name: 'Customer',
  components: {}
})
export default class Customer extends Vue {
  @Prop({ default: {} }) private commonData!: any
  @Prop({ default: '' }) private moduleType!: string // 每个模块的微前端ID

  private $bus: any
  private $store: any
  private $router: any
  private $message: any
  private $getCache: any
  private customerMicApp: any
  private mpWorksheetDict: any = {
    name: '111', // 客户名称 75cf0d3835724ea089c09c7d18a4dc21
    phone: '222', // 客户名称 116385a0298b11eba9c0bf34f507af14
    callSheetId: '333', // 通话Id 116293902d6211ebbdc3c9f1f40b76e7
    source: '444' // 客户来源 125fdf502d6211ebbdc3c9f1f40b76e7
  }

  private initMicroApp (store: object) {
    this.customerMicApp = loadMicroApp(
      {
        name: 'apass-micro-customerData',
        entry: `${(CommonModule.initConfig as any).platformConfig.mopowerUrl}/sheetRecord.html`,
        // entry: 'http://172.16.88.180:8080/sheetRecord.html',
        container: `#apassMicroCustomerData_${this.moduleType}`,
        props: {
          callEvent: true, // 是否展示电话字段处的[打电话、发短信]功能
          routerBase: this.$router.currentRoute.path,
          store,
          user: {
            id: this.$store.state.common.mpInfo.mpUserId,
            companyId: this.$store.state.common.mpInfo.mpCompanyId
          }
        }
      },
      {
        sandbox: {
          // experimentalStyleIsolation: true
        }
      }
    )
    addGlobalUncaughtErrorHandler(event => {
      // console.log(6666, event)
    })
    // 因为第一次加载比较慢，防止失败所以在timeout之后再修改一次
    // this.changeQianKunDom()
    // setTimeout(() => {
    //   this.changeQianKunDom()
    // }, 1000)
  }

  private unmountMicroApp () {
    if (this.customerMicApp && JSON.stringify(this.customerMicApp) !== '{}') {
      this.customerMicApp.mountPromise.then(() => {
        this.customerMicApp.unmount()
      })
    }
  }

  private handleSaveFunc (oldData: any, type: string) {
    const data = JSON.parse(JSON.stringify(oldData))
    const dict = JSON.parse(JSON.stringify(this.mpWorksheetDict))
    for (const k in dict) {
      const v = dict[k]
      dict[v] = k
      delete dict[k]
    }
    for (const k in data) {
      if (dict[k]) {
        data[dict[k]] = data[k]
        delete data[k]
      }
    }
    if (Object.keys(dict).length === 0) {
      console.error('/customer/config/cache接口返回的数据有问题')
    }
    if (type === 'add') { // 新增客户
      this.$emit('afterAddCustRecord', data)
    } else if (type === 'edit') { // 修改客户
      this.$emit('afterEditCustRecord', data)
    }
  }

  private changeQianKunDom () {
    if ((document as any).getElementsByClassName('drawer-main')[0]) {
      (document as any).getElementsByClassName('drawer-main')[0].style['border-radius'] = '10px'
    }
  }

  @Watch('commonData', { immediate: true })
  private commonDataChange (newData) {
    CommonModule.getMpInfo({ url: '/auth/get/mp/relation', method: 'POST', data: {} }).then(() => {
      this.$getCache('/crm/action/customer/config/cache', ['customerList'], false).then((cache: any) => {
        this.mpWorksheetDict = cache.customerList[0]
        const store = {
          hiddenHeader: true, // 隐藏一些东西
          backInfo: {}, // 需要提前展示或加入的数据
          recordId: (typeof newData === 'object' && newData.custId) ? newData.custId : '', // 客户Id ==> 一条数据的id
          applicationId: this.$store.state.common.mpInfo.mpApplicationId, // 应用id
          worksheetId: this.$store.state.common.mpInfo.mpCrmWorksheetId // 客户模板id
        }
        this.$set(store, 'handleSaveFunc', (type, that, data) => {
          if (type === 'add') { // 新增客户后进行回显
            that.initForm(data, true) // mp的回调
            this.handleSaveFunc(data, 'add') // v7的回调
          } else if (type === 'edit') { // 修改客户
            // data.id = newData.custId // 修改客户的时候，没返回id字段，现在加了
            this.handleSaveFunc(data, 'edit') // v7的回调
          }
        })
        // mopower 打电话发短信的回调事件
        this.$set(store, 'handleCallMessage', mpCallMsgEvent);
        if (newData.callSheetId) { // 有通话的数据
          store.backInfo = {
            [this.mpWorksheetDict.phone]: newData.phone,
            [this.mpWorksheetDict.callSheetId]: newData.callSheetId,
            [this.mpWorksheetDict.source]: '通话卡片'
          }
        }
        this.$nextTick(() => {
          if (this.customerMicApp && JSON.stringify(this.customerMicApp) !== '{}') {
            this.customerMicApp.mountPromise.then(() => {
              this.customerMicApp.update({
                type: 'changeRecord',
                callEvent: true, // 是否展示电话字段处的[打电话、发短信]功能
                data: store
              })
            })
          } else {
            this.initMicroApp(store)
          }
        })
      })
    })
  }
}
</script>

<style lang="stylus" scoped>
.customer
  height 100%
  overflow auto
.customer-data-page
  height 100%
  overflow auto
  .page-container
    height 100%
    background white url('../../../assets/img/loading.gif') no-repeat center center
    background-size 1.2 1.2
</style>
